<template>
  <div class="Login_root__xpMLV">
    <!-- 导航栏 -->
    <div class="nav">
      <van-icon name="arrow-left" @click="toHome" />
      <van-nav-bar class="page-nav-bar" title="账号登录" />
    </div>

    <!-- 登录表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        placeholder="请输入账号"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        placeholder="请输入密码"
        :rules="[{ pattern, message: '密码不少于6位数' }]"
      />
      <div style="margin: 12px" class="login-btn-wrap">
        <van-button
          color="#21b97a"
          class="login-btn"
          size="large"
          square
          block
          type="info"
          native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>

    <!-- 注册 -->
    <div class="register">
      <van-cell title="还没有账号，去注册~" to="/register" />
    </div>
  </div>
</template>

<script>
import { loginAPI } from "@/api";

export default {
  data() {
    return {
      username: "",
      password: "",
      pattern: /\d{6}/,
    };
  },
  methods: {
    // 表单提交发送请求
    async onSubmit() {
      // 调用加载函数
      this.loading();
      try {
        const {
          data: { description, body },
        } = await loginAPI({
          username: this.username,
          password: this.password,
        });
        console.log(body);
        // 保存token
        this.$store.commit("user/SET_TOKEN", body.token);
        // 登录成功后跳转我的页面
        this.$router.push("/layout/my");
        // 弹成功提示
        this.$toast.success(description);
      } catch (err) {
        // console.log(err);
        // 失败原因
        this.$toast.fail(description);
      }
    },
    // 封装loading函数
    loading() {
      // 开始转圈圈
      this.$toast.loading({
        duration: 0, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: "登录中...", // 提示消息
      });
    },
    // 点击图标去往Home
    toHome() {
      this.$router.push({
        path: "/layout/my",
      });
    },
  },
};
</script>

<style scoped lang="less">
.Login_root__xpMLV {
  height: 100%;
  .nav {
    position: relative;
    .van-icon {
      position: absolute;
      top: 16px;
      left: 16px;
      z-index: 3;
      font-size: 16px;
      color: #fff;
    }
    .page-nav-bar {
      margin-bottom: 21px;
      background-color: #21b97a;
      :deep(.van-nav-bar__title) {
        color: #fff;
        font-size: 18px;
      }
    }
  }
  .van-cell {
    height: 60px;
    font-size: 16px;
    line-height: 50px;
  }

  .login-btn-wrap {
    .login-btn {
      margin: 40px 0 20px;
    }
  }
  .register {
    text-align: center;
    .van-cell {
      font-size: 14px;
      color: #666;
    }
  }
}
</style>
